package com.app.couponsharelife.ui.main.me.setting

import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Handler
import android.os.Message
import android.view.View
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import cn.sharesdk.framework.Platform
import cn.sharesdk.framework.PlatformActionListener
import cn.sharesdk.framework.ShareSDK
import cn.sharesdk.wechat.friends.Wechat
import com.bilibili.boxing.Boxing
import com.bilibili.boxing.model.entity.impl.ImageMedia
import com.bilibili.boxing.utils.ImageCompressor
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.Target
import com.google.gson.Gson
import com.hwangjr.rxbus.RxBus
import com.hwangjr.rxbus.annotation.Subscribe
import com.hwangjr.rxbus.annotation.Tag
import com.hwangjr.rxbus.thread.EventThread
import com.app.couponsharelife.R
import com.app.couponsharelife.base.BaseActivity
import com.app.couponsharelife.data.bean.RemoteResultBean
import com.app.couponsharelife.data.bean.UserCenterBean
import com.app.couponsharelife.data.remote.retrofit.RetrofitWorker
import com.app.couponsharelife.databinding.ActivitySettingBinding
import com.app.couponsharelife.jpush.TagAliasOperatorHelper
import com.app.couponsharelife.manage.Contacts
import com.app.couponsharelife.ui.dialog.ExitSureDialog
import com.app.couponsharelife.ui.listener.OnClickListener
import com.app.couponsharelife.ui.main.login.NewLoginActivity
import com.app.couponsharelife.ui.main.login.forgetpwd.ForgetPasswordActivity
import com.app.couponsharelife.ui.main.me.bindalipay.BindAlipayActivity
import com.app.couponsharelife.ui.main.me.label.UserLabelActivity
import com.app.couponsharelife.ui.main.me.phonenum.BindPhoneNumActivity
import com.app.couponsharelife.ui.main.me.phonenum.UpdatePhoneNumActivity
import com.app.couponsharelife.ui.viewmodel.MeViewModel
import com.app.couponsharelife.utils.AppUtils
import com.app.couponsharelife.utils.DataCleanManager
import com.app.couponsharelife.utils.Logger
import com.app.fuquan.data.bean.PageStatus
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.observers.DisposableObserver
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_setting.*
import okhttp3.MediaType
import okhttp3.RequestBody
import java.lang.ref.WeakReference
import java.util.*
import java.util.concurrent.TimeUnit

/**
 * 设置界面
 * */
class SettingActivity : BaseActivity() {
    override val viewLayoutId: Int get() = R.layout.activity_setting
    private var mViewModel: MeViewModel? = null
    private val REQUEST_CODE = 101
    private var isEdit = false
    private var type = 0
    private var path = ""
    private var name = ""
    private var mobile=""
    private var userId=""
    private var userName=""
    private var unionId=""
    private var headPrice=""
    private val handler=MyHandler(this)
    private var disposable: Disposable? = null
    private var sex="1"
    private var city=""
    private var province=""
    private var isvisible=false
    private var isWXBunding=false
    override fun initViews() {
        AppUtils.initImmersionBar(this,false)
        initClickEvent()
        //tvChangeUserVersion.text = AppUtils.getVersionName()
    }

    private fun initClickEvent() {
        (mViewDataBinding as ActivitySettingBinding).listener = View.OnClickListener {
            when (it.id) {
                R.id.ivBack -> finish()
                /*R.id.tvUserName, R.id.ivEditName -> {
                    UpdateUserNameDialog(this, R.style.DialogStyle, object : OnClickListener {
                        override fun click(arg1: Int, arg2: Any) {
                            if (arg2 == "") {
                                showToastMsg("请输入新用户名")
                            } else {
                                name = arg2 as String
                                type = 1
                                updateUserName()
                            }
                        }
                    }).show()
                }*/
                /*R.id.ivUserImage -> {
                    val videoConfig = BoxingConfig(BoxingConfig.Mode.SINGLE_IMG).needCamera(R.drawable.camera_white_icon)
                    Boxing.of(videoConfig).withIntent(this, BoxingActivity::class.java).start(this, REQUEST_CODE)
                }*/
                R.id.tvChangeUserLabel, R.id.ivUserLabelArrow -> {
                    startActivity(Intent(this, UserLabelActivity::class.java))
                }
                R.id.tvChangeUserAlipay, R.id.ivUserAlipayArrow -> {
                    if (mobile.isEmpty()){
                        showToastMsg("请先绑定手机号")
                        //startActivity(Intent(this, BindPhoneNumActivity::class.java))
                        val intent=Intent(this, BindPhoneNumActivity::class.java)
                        intent.putExtra("Type","Setting")
                        startActivity(intent)
                    }else{
                        val intent = Intent(this, BindAlipayActivity::class.java)
                        intent.putExtra("isWithdraw", false)
                        intent.putExtra("Mobile",mobile)
                        startActivity(intent)
                    }
                }
                R.id.tvChangeUserPhone, R.id.ivUserPhoneArrow -> {
                    if (mobile.isEmpty())
                        startActivity(Intent(this, BindPhoneNumActivity::class.java))
                    else {
                        val intent = Intent(this, UpdatePhoneNumActivity::class.java)
                        intent.putExtra("phone", mobile)
                        startActivity(intent)
                    }
                }
                R.id.tvChangeUserPassWord, R.id.ivUserPassWordArrow -> {
                    startActivity(Intent(this, ForgetPasswordActivity::class.java))
                }
                R.id.tvChangeUserVersion, R.id.ivUserVersionArrow -> {  //绑定微信
                    //startActivity(Intent(this, UpdateVersionActivity::class.java))
                    if (isWXBunding){
                        showToastMsg("您已经绑定过微信了！")
                    }else{
                        startWX()
                    }
                }
                R.id.tvChangeUserCache -> {
                    DataCleanManager.clearAllCache(this)
                    initAppCacheSize()
                    showToastMsg("缓存清除成功")
                }
                R.id.tvLogOut -> {
                    ExitSureDialog(this, R.style.DialogStyle, object : OnClickListener {
                        override fun click(arg1: Int, arg2: Any) {
                            //userLogOut()
                            mViewModel!!.freshUserLogOut(hashMapOf(), false)
                            deleteAlias()
                            AppUtils.setString(Contacts.TOKEN, "")
                            AppUtils.setString(Contacts.USERTYPE, "")
                            AppUtils.setString(Contacts.USERID, "")
                            AppUtils.setString(Contacts.ADZONE_ID, "")
                            AppUtils.setString(Contacts.COMMISSION_RATIO,"")
                            startActivity(Intent(this@SettingActivity, NewLoginActivity::class.java))
                            finishActivityManager.finishAllActivity()
                        }
                    }).show()
                }
            }
        }
    }
    private fun startWX(){
        val wechat= ShareSDK.getPlatform(Wechat.NAME)
        wechat.removeAccount(true)
        //wechat.SSOSetting(true)
        wechat!!.platformActionListener=object : PlatformActionListener {
            override fun onComplete(p0: Platform, p1: Int, p2: HashMap<String, Any>) {
                //Log.e("eeee","---->"+p0.db.userId+"---"+p0.db["unionid"]+"---"+p0.db.userName+"---"+p0.db.userIcon)
                //wxLogin(p0.db.userId,p0.db["unionid"],p0.db.userName,p0.db.userIcon)
                isvisible=false
                userId=p0.db.userId
                unionId=p0.db["unionid"]
                userName=p0.db.userName
                headPrice=p0.db.userIcon
                sex=p0.db["sex"]
                city=p0.db["city"]
                province=p0.db["province"]
                val msg= Message()
                msg.what=0
                handler.sendMessage(msg)
            }

            override fun onCancel(p0: Platform?, p1: Int) {
                isvisible=false
            }

            override fun onError(p0: Platform?, p1: Int, p2: Throwable?) {
                //showToastMsg("登录失败")
                isvisible=false
            }
        }
        if (wechat.isAuthValid) {
            wechat.removeAccount(true)
            return
        }
        wechat.showUser(null)
        isvisible=true
    }
    private fun initAppCacheSize() {
        try {
            val totalCacheSize = DataCleanManager.getTotalCacheSize(this)
            println(totalCacheSize)
            if (totalCacheSize.substring(0, totalCacheSize.length - 1) == "0.0") {
                tvChangeUserCache.setTextColor(ContextCompat.getColor(this, R.color.act_login_edit_text_hint_text_color))
                tvChangeUserCache.setBackgroundResource(R.drawable.act_setting_no_cache_bg)
            } else {
                tvChangeUserCache.setTextColor(ContextCompat.getColor(this, R.color.fra_order_item_price_text_color))
                tvChangeUserCache.setBackgroundResource(R.drawable.shape_red_ff0_ff4)
            }
        } catch (e: Exception) {
            tvChangeUserCache.setTextColor(ContextCompat.getColor(this, R.color.act_login_edit_text_hint_text_color))
            tvChangeUserCache.setBackgroundResource(R.drawable.act_setting_no_cache_bg)
            e.printStackTrace()
        }
    }

    private fun userLogOut() {
        val map = HashMap<String, String>()
        map[Contacts.TOKEN] = AppUtils.getString(Contacts.TOKEN, "")
        map["timestamp"] = (System.currentTimeMillis() / 1000).toString()
        map["sign"] = AppUtils.getMapString(map)
        map["param"] = Gson().toJson(TreeMap(map).descendingMap())
        mViewModel!!.freshUserLogOut(map, true)
    }

    override fun initViewModel() {
        if (mViewModel == null) mViewModel = ViewModelProviders.of(this).get(MeViewModel::class.java)
        if (!mViewModel!!.userLogOut()!!.hasObservers()) {
            mViewModel!!.userLogOut()!!.observe(this, Observer {
                if (it == null) {
                    dismissProgressDialog()
                    showToastMsg("数据出错啦")
                    return@Observer
                }
                when (it.status) {
                    PageStatus.Loading -> {
                        showProgressDialog("请稍候")
                    }
                    PageStatus.Error -> {
                        dismissProgressDialog()
                        mViewModel!!.freshUserLogOut(hashMapOf(), false)
                        showToastMsg(parseErrorDate(it.error!!.message).tip)
                    }
                    PageStatus.Empty -> {
                        dismissProgressDialog()
                        mViewModel!!.freshUserLogOut(hashMapOf(), false)
                        showToastMsg("数据出错啦")
                    }
                    PageStatus.Content -> {
                        dismissProgressDialog()
                        mViewModel!!.freshUserLogOut(hashMapOf(), false)
                        if (it.data!!.code == 1 && it.data.data != null) {
                            AppUtils.setString(Contacts.TOKEN, "")
                            AppUtils.setString(Contacts.USERTYPE, "")
                            AppUtils.setString(Contacts.USERID, "")
                            AppUtils.setString(Contacts.ADZONE_ID, "")
                            AppUtils.setString(Contacts.UNIONID, "")
                            startActivity(Intent(this, NewLoginActivity::class.java))
                            finishActivityManager.finishAllActivity()
                        } else {
                            showToastMsg("退出失败")
                        }
                    }
                }
            })
            mViewModel!!.userCenter()!!.observe(this, Observer {
                if (it == null) {
                    dismissProgressDialog()
                    showToastMsg("数据出错啦")
                    return@Observer
                }
                when (it.status) {
                    PageStatus.Loading -> {
                        showProgressDialog("请稍候")
                    }
                    PageStatus.Error -> {
                        dismissProgressDialog()
                        mViewModel!!.freshUserCenter(hashMapOf(), false)
                        showToastMsg(parseErrorDate(it.error!!.message).tip)
                    }
                    PageStatus.Empty -> {
                        dismissProgressDialog()
                        mViewModel!!.freshUserCenter(hashMapOf(), false)
                        showToastMsg("数据出错啦")
                    }
                    PageStatus.Content -> {
                        mViewModel!!.freshUserCenter(hashMapOf(), false)
                        if (it.data!!.code == 200 && it.data.data != null) {
                            handleContent(it.data.data!!)
                        } else {
                            dismissProgressDialog()
                            showToastMsg("获取失败")
                        }
                    }
                }
            })
            mViewModel!!.updateUser()!!.observe(this, Observer {
                if (it == null) {
                    dismissProgressDialog()
                    showToastMsg("数据出错啦")
                    return@Observer
                }
                when (it.status) {
                    PageStatus.Loading -> {
                        showProgressDialog("请稍候")
                    }
                    PageStatus.Error -> {
                        dismissProgressDialog()
                        mViewModel!!.freshUpdateUser(hashMapOf(), false)
                        showToastMsg(parseErrorDate(it.error!!.message).tip)
                    }
                    PageStatus.Empty -> {
                        dismissProgressDialog()
                        mViewModel!!.freshUpdateUser(hashMapOf(), false)
                        showToastMsg("数据出错啦")
                    }
                    PageStatus.Content -> {
                        dismissProgressDialog()
                        mViewModel!!.freshUpdateUser(hashMapOf(), false)
                        if (it.data!!.code == 200) {
                            isEdit = true
                            if (type == 1) {
                                showToastMsg("用户名修改成功")
                                tvUserName.text = name
                            } else if (type == 2) {
                                initBackGround(Contacts.REMOTE_IMAGE_URL + path)
                                showToastMsg("头像修改成功")
                            }
                        } else {
                            if (type == 1) {
                                showToastMsg("用户名修改失败")
                            } else if (type == 2) {
                                showToastMsg("头像修改失败")
                            }
                        }
                    }
                }
            })
            mViewModel!!.uploadPicBase64()!!.observe(this, Observer {
                if (it == null) {
                    dismissProgressDialog()
                    showToastMsg("数据出错啦")
                    return@Observer
                }
                when (it.status) {
                    PageStatus.Loading -> {
                        showProgressDialog("请稍候")
                    }
                    PageStatus.Error -> {
                        dismissProgressDialog()
                        mViewModel!!.freshUploadPicBase64(hashMapOf(), false)
                        showToastMsg(parseErrorDate(it.error!!.message).tip)
                    }
                    PageStatus.Empty -> {
                        dismissProgressDialog()
                        mViewModel!!.freshUploadPicBase64(hashMapOf(), false)
                        showToastMsg("数据出错啦")
                    }
                    PageStatus.Content -> {
                        mViewModel!!.freshUploadPicBase64(hashMapOf(), false)
                        if (it.data!!.code == 200 && it.data.data != null && it.data.data is String) {
                            path = it.data.data as String
                            updateUserImage()
                        } else {
                            dismissProgressDialog()
                            showToastMsg("头像上传失败，请重新选择")
                        }
                    }
                }
            })
            loadData()
        }
    }
    @Subscribe(thread = EventThread.MAIN_THREAD, tags = [(Tag("mefrg_fraeshdata"))])
    fun refreshData(fresh: String) {
        loadData()
    }
    private fun handleContent(data: UserCenterBean) {
        AppUtils.setString(Contacts.USER_MOBILE,data.mobile)
        val headUrl= when {
            data.headimgurl.startsWith("/") -> Contacts.REMOTE_IMAGE_URL + data.headimgurl
            data.headimgurl.startsWith("//") -> Contacts.TCP + data.headimgurl
            else -> data.headimgurl
        }
        initBackGround(headUrl)
        tvUserName.text = data.nickName
        mobile=data.mobile?:""
        tvChangeUserAlipay.text = if (data.alipay == "") "绑定" else data.alipay
        if (mobile.length==11){
            val start = mobile.substring(0, 3)
            val end = mobile.substring(7)
            tvChangeUserPhone.text = String.format("${start}****$end")
        }else {
            tvChangeUserPhone.text = if (mobile == "") "绑定手机号" else mobile
        }
        tvChangeUserVersion.text=if (data.unionId == "") {
            isWXBunding=false
            "绑定微信"
        } else {
            isWXBunding=true
            data.nickName
        }
    }

    private fun initBackGround(image: String) {
        Glide.with(this).asBitmap().apply(RequestOptions().circleCrop())
                .load(image)
                .listener(object : RequestListener<Bitmap> {
                    override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<Bitmap>?, isFirstResource: Boolean): Boolean {
                        ivUserImage.setImageResource(R.drawable.ic_tribe_boy_thumb)
                        return true
                    }

                    override fun onResourceReady(resource: Bitmap?, model: Any?, target: Target<Bitmap>?, dataSource: DataSource?, isFirstResource: Boolean): Boolean {
                        if (resource != null) {
                            ivUserImage.setImageBitmap(resource)
                            return true
                        }
                        return false
                    }
                }).into(ivUserImage)
        /*Glide.with(this).asBitmap()
                .load(image)
                .apply(RequestOptions())
                .listener(object : RequestListener<Bitmap> {
                    override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<Bitmap>?, isFirstResource: Boolean): Boolean {
                        val resource = BitmapFactory.decodeResource(resources, R.drawable.ic_tribe_boy_thumb)
                        var overlay = resource.copy(resource.config, true)
                        overlay = Blur.onStackBlur(overlay, 5)
                        ivBackGround.setImageBitmap(overlay)
                        clActSettingContainer.visibility = View.VISIBLE
                        ivUserImage.visibility = View.VISIBLE
                        dismissProgressDialog()
                        return true
                    }

                    override fun onResourceReady(resource: Bitmap?, model: Any?, target: Target<Bitmap>?, dataSource: DataSource?, isFirstResource: Boolean): Boolean {
                        if (resource != null) {
                            var overlay = resource.copy(resource.config, true)
                            overlay = Blur.onStackBlur(overlay, 10)
                            ivBackGround.setImageBitmap(overlay)
                            clActSettingContainer.visibility = View.VISIBLE
                            ivUserImage.visibility = View.VISIBLE
                            dismissProgressDialog()
                            return true
                        }
                        clActSettingContainer.visibility = View.VISIBLE
                        ivUserImage.visibility = View.VISIBLE
                        dismissProgressDialog()
                        return false
                    }
                })
                .into(ivBackGround)*/
        dismissProgressDialog()
    }

    fun loadData() {
        val map = HashMap<String, String>()
        map["userId"] = AppUtils.getString(Contacts.USERID, "")
        mViewModel?.freshUserCenter(map, true)
    }

    fun updateUserName() {
        val map = HashMap<String, String>()
        map["userId"] = AppUtils.getString(Contacts.USERID, "")
        map["nickName"] = name
        map["timestamp"] = System.currentTimeMillis().toString()
        map["sign"] = AppUtils.getMapString(map)
        mViewModel?.freshUpdateUser(map, true)
    }

    private fun uploadPicBase64() {
        val map = HashMap<String, String>()
        map["base64String"] = "data:image/jpg;base64," + AppUtils.encodeImage(BitmapFactory.decodeFile(path))
        mViewModel?.freshUploadPicBase64(map, true)
    }

    private fun updateUserImage() {
        val map = HashMap<String, String>()
        map["userId"] = AppUtils.getString(Contacts.USERID, "")
        map["headimgurl"] = path
        map["timestamp"] = System.currentTimeMillis().toString()
        map["sign"] = AppUtils.getMapString(map)
        mViewModel?.freshUpdateUser(map, true)
    }
    private fun bindingWX(openId:String,unionId:String,nickName:String,headPrice:String){
        val map = HashMap<String, String>()
        map["userId"] = AppUtils.getString(Contacts.USERID, "")
        map["openId"] = openId
        map["unionId"] = unionId
        map["nickName"] = nickName
        map["headPic"] = headPrice
        map["timestamp"] = System.currentTimeMillis().toString()
        map["sign"] = AppUtils.getMapString(map)
        //mViewModel?.freshWxLogin(map,true)
        RetrofitWorker.retrofitWorker.bindWX(RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), Gson().toJson(map)))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : DisposableObserver<RemoteResultBean<String>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<String>) {
                        dismissProgressDialog()
                        if (it.code == 200) {
                            showToastMsg("绑定成功")
                            AppUtils.setString(Contacts.UNIONID, unionId)
                            loadData()
                        } else {
                            showToastMsg("请求失败")
                        }
                    }

                    override fun onError(e: Throwable) {
                        dismissProgressDialog()
                    }
                })
    }
    override fun onResume() {
        super.onResume()
        if (isvisible){
            showProgressDialog("请稍后...")
        }
        if (disposable == null)
            disposable = Observable.interval(0, 2, TimeUnit.SECONDS)//10s 倒计时
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe({ aLong -> if (aLong != 0L) dismissProgressDialog() }) { dismissProgressDialog() }
    }
    override fun onBackPressed() {
        if (isEdit) {
            RxBus.get().post("freshBalance", "")
        }
        super.onBackPressed()
    }

    override fun onDestroy() {
        super.onDestroy()
        AppUtils.destroyImmersionBar(this)
    }
    //头像选择回调
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == 0) {
            return
        }
        if (data == null) {
            return
        }
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CODE) {
                val medias = Boxing.getResult(data)
                if (medias != null) {
                    (medias[0] as ImageMedia).compress(ImageCompressor(this))
                    if ((medias[0] as ImageMedia).compressPath != null) {
                        path = (medias[0] as ImageMedia).compressPath
                        type = 2
                        uploadPicBase64()
                    } else {
                        showToastMsg("头像上传失败，请重新选择")
                    }
                }
            }
        }
    }
    private fun deleteAlias() {
        AppUtils.setString(Contacts.JPUSH_ALIAS,"false") //别名是否已经设置
        val alias = AppUtils.getString(Contacts.USERID, "")//别名
        Logger.e("settingactivity",  "删除别名")
        if ( alias.isNotEmpty()) {
            //设置别名或标签
            val tagAliasBean = TagAliasOperatorHelper.TagAliasBean()
            tagAliasBean.alias=alias
            tagAliasBean.action = TagAliasOperatorHelper().ACTION_DELETE
            tagAliasBean.isAliasAction =true
            TagAliasOperatorHelper().getInstance()?.handleAction(applicationContext, 1, tagAliasBean)
        }
    }
    @Subscribe(thread = EventThread.MAIN_THREAD, tags = [(Tag("freshUserInfo"))])
    fun receiveData(fresh: String) {
        loadData()
    }
    private class MyHandler(activity: SettingActivity) : Handler() {
        private val mActivity: WeakReference<SettingActivity> = WeakReference<SettingActivity>(activity)
        private var activity:SettingActivity?=null
        override fun handleMessage(msg: Message) {
            if (activity== null) {
                activity=mActivity.get()
            }
            when (msg.what) {
                0 -> {
                    activity!!.bindingWX(activity!!.userId,activity!!.unionId,activity!!.userName,activity!!.headPrice)
                }
                else -> {

                }
            }
        }
    }
}
